/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 ManagedServer.cpp. Created on: 14.09.2009 15:53:35
 */

#include "smartobjects/network/ManagedServer.hpp"
#include "smartobjects/network/EndpointLocation.hpp"
#include "smartobjects/network/ManagedServerConnection.hpp"

namespace smartobjects {

ManagedServer::ManagedServer(INetworkFactory* poFactory) :
		m_poNetworkFactory(poFactory),
		m_bStarted(false),
		m_poEndpointLocation(NULL),
		m_poEndpointCoordinator(NULL) {
	m_poNetworkFactory->addRef();
}

ManagedServer::~ManagedServer() {
	stop();

	boost::recursive_mutex::scoped_lock oLock(m_mxAcceptors);
	for( AcceptorsMap::iterator it = m_mAcceptors.begin(); it!=m_mAcceptors.end(); it++ ) {
		it->second->release();
	}
	m_mAcceptors.clear();
	oLock.unlock();

	releaseAndClear(m_poNetworkFactory);

	oLock.lock();
	if(m_poEndpointCoordinator)
		m_poEndpointCoordinator->resetManagedConnectionFactory();
	releaseAndClear(m_poEndpointCoordinator);
	releaseAndClear(m_poEndpointLocation);
}

void ManagedServer::addListener(IManagedServerListener* poListener) {
	boost::recursive_mutex::scoped_lock oLock ( m_mxServerListeners );
	if( !m_oPALServerListeners.isActivated() ) {
		m_aServerListeners.push_back(poListener);
	}
	else {
		m_oPALServerListeners.putListenerToAdd(poListener);
	}

}

void ManagedServer::delListener(IManagedServerListener* poListener) {
	boost::recursive_mutex::scoped_lock oLock ( m_mxServerListeners );
	if( !m_oPALServerListeners.isActivated() ) {
		m_aServerListeners.remove(poListener);
	}
	else {
		m_oPALServerListeners.putListenerToRemove(poListener);
	}
}

void ManagedServer::processingPostActionServerListeners() {
	m_oPALServerListeners.deactivate();
	foreach( PostActionListenersContainer<IManagedServerListener>::PostActionQueueItem item, m_oPALServerListeners.getPostActionQueue()) {
		if(item.isActionToAdd()) {
			addListener( item.getListener() );
		}
		else
		if(item.isActionToRemove()) {
			delListener( item.getListener() );
		}
	}
	m_oPALServerListeners.reset();
}

void ManagedServer::setEndpointLocation(IEndpointLocation* poLocation, IEndpointCoordinator* poCoordinator) {
	boost::recursive_mutex::scoped_lock oLock(m_mxAcceptors);
	setNewRefObject(m_poEndpointLocation, poLocation);
	setNewRefObject(m_poEndpointCoordinator, poCoordinator);
	if ( m_poEndpointCoordinator ) {
		m_poEndpointCoordinator->setManagedConnectionFactory(
				this
		);
	}
}

IEndpointLocation* ManagedServer::getEndpointLocation() {
	return m_poEndpointLocation;
}

void ManagedServer::start() {
	boost::recursive_mutex::scoped_lock oServerLock(m_mxServer);
	boost::recursive_mutex::scoped_lock oLock(m_mxAcceptors);
	updateAcceptors();
	for( AcceptorsMap::iterator it = m_mAcceptors.begin(); it!=m_mAcceptors.end(); it++ ) {
		it->second->start();
	}
	m_bStarted= true;

}

void ManagedServer::stop() {

	boost::recursive_mutex::scoped_lock oServerLock(m_mxServer);
	boost::recursive_mutex::scoped_lock oAcceptorsLock(m_mxAcceptors);
	m_bStarted = false;
	for( AcceptorsMap::iterator it = m_mAcceptors.begin(); it!=m_mAcceptors.end(); it++ ) {
		it->second->stop();
	}
	oAcceptorsLock.unlock();

	boost::recursive_mutex::scoped_lock oConnectionsLock(m_mxConnections);
	ServerConnections aTempConnections = m_aConnections;
	m_aConnections.clear();
	oConnectionsLock.unlock();

	oAcceptorsLock.lock();
	for( Handlers::iterator it = m_aAllHandlers.begin(); it!=m_aAllHandlers.end(); it++ ) {
		(*it)->getConnection()->delConnectionListener(*it);
		(*it)->getConnection()->delStreamListener(*it);
		if(m_poEndpointCoordinator)
			m_poEndpointCoordinator->onRemoved(*it);
		(*it)->release();
	}
	m_aAllHandlers.clear();
	for( ServerConnections::iterator it = aTempConnections.begin(); it!=aTempConnections.end(); it++ ) {
		(*it)->stop();
		(*it)->release();
	}
	aTempConnections.clear();
}

void ManagedServer::updateAcceptors() {
	boost::recursive_mutex::scoped_lock oLock(m_mxAcceptors);
	AcceptorsMap mTempAcceptors = m_mAcceptors;
	m_mAcceptors.clear();
	foreach ( URI* poURI, m_poEndpointLocation->getLocations() ) {
		std::string sKey = poURI->getHost() + ":" + boost::lexical_cast<std::string>(poURI->getPort());
		AcceptorsMap::iterator itExistAcceptor = mTempAcceptors.find(sKey);
		if(itExistAcceptor!=mTempAcceptors.end()) {
			m_mAcceptors.insert(*itExistAcceptor);
			mTempAcceptors.erase(itExistAcceptor);
		}
		else {
			IAcceptor* poAcceptor = m_poNetworkFactory->createAcceptor();
			poAcceptor->setEndpointURI( poURI );
			poAcceptor->addListener(this);

			std::pair<std::string, IAcceptor*> oAcceptorPair ( sKey, poAcceptor );

			m_mAcceptors.insert( oAcceptorPair );

			if(m_bStarted)
				poAcceptor->start();
		}
	}

	for( AcceptorsMap::iterator it = mTempAcceptors.begin(); it!=mTempAcceptors.end(); it++ ) {
		it->second->stop();
		it->second->release();
	}

}

void ManagedServer::onAccepted ( IConnection* poConnection ) throw() {
	boost::recursive_mutex::scoped_lock oLock(m_mxAcceptors);
	if(!m_bStarted)
		return;

	ConnectionHandler* poHandler (
			new ConnectionHandler(
					poConnection,
					m_poEndpointCoordinator
			)
	);
	m_aAllHandlers.insert(poHandler);

	poConnection->addConnectionListener(poHandler);
	poConnection->addStreamListener(poHandler);

	fireOnConnected(poHandler);
	poHandler->onConnected(poConnection);
}

void ManagedServer::fireOnConnected(IManagedConnection* poConnection) {
	boost::recursive_mutex::scoped_lock oLock(m_mxServerListeners);
	m_oPALServerListeners.activate();
	foreach(IManagedServerListener* poListener, m_aServerListeners) {
		poListener->onConnected( poConnection );
	}
	processingPostActionServerListeners();

}
void ManagedServer::fireOnConnected(ConnectionHandler* poHandler) {
	boost::recursive_mutex::scoped_lock oLock(m_mxServerListeners);
	m_oPALServerListeners.activate();
	foreach(IManagedServerListener* poListener, m_aServerListeners) {
		poListener->onConnected( poHandler );
	}
	processingPostActionServerListeners();
}

void ManagedServer::removeHandler(ConnectionHandler* poHandler) {
	boost::recursive_mutex::scoped_lock oLock(m_mxAcceptors);
	if(m_aAllHandlers.find(poHandler)!=m_aAllHandlers.end()) {
		m_aAllHandlers.erase(poHandler);
		if(m_poEndpointCoordinator)
			m_poEndpointCoordinator->onRemoved(poHandler);
		poHandler->release();
	}
}


IManagedConnection* ManagedServer::createManagedConnection() {
	boost::recursive_mutex::scoped_lock oConnectionsLock(m_mxConnections);
	IManagedConnection* poResult = new ManagedServerConnection(this, m_poEndpointCoordinator);
	m_aConnections.insert(poResult);
	return poResult;
}

void ManagedServer::removeManagedConnection(IManagedConnection* poConnection) {
	boost::recursive_mutex::scoped_lock oConnectionsLock(m_mxConnections);
	if(m_aConnections.find(poConnection)!=m_aConnections.end()) {
		m_aConnections.erase(poConnection);
		poConnection->release();
	}
}

}
